package m3;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;

public class Consumer {
    public static void main(String[] args) throws Exception{
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
//        f.setPort(5672);    //默认端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //1.定义随机队列  2.定义交换机  3.绑定
        // 定义随机队列的两种方式: 所有参数手动提供/由服务器自动创建
        String queue = UUID.randomUUID().toString();
        /*
        参数:
            1:队列名
            2.是否是持久队列(非持久队列服务器重启后会消失)
            3.是否是排他(独占)队列
            4.是否自动删除
            5.队列其他属性
         */
        c.queueDeclare(queue, false, true, true, null);
        c.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);
        //绑定
        c.queueBind(queue, "logs", "");//第三个参数对于fanout交换机无效

        //正常的从随机队列接收消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到:"+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };
        c.basicConsume(queue, true, deliverCallback, cancelCallback);

    }
}
